package com.tinem.platform.web.tool.controller;

import com.tinem.platform.module.pojo.enums.web.LinkType;
import com.tinem.platform.module.pojo.vo.link.EventReq;
import com.tinem.platform.module.pojo.vo.link.EventRes;
import com.tinem.platform.module.starter.sdk.api.LinkService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;

/**
 * @author fengzhihao
 * @version v1
 * @program: platform
 * @className LinkController
 * @description TODO
 * @site 
 * @company 
 * @create 2020-07-13 19:53
 */
@Slf4j
@Controller
public class LinkController {
    @Resource
    LinkService linkService;

    @GetMapping("/{linkId}")
    @ResponseBody
    public Object open(@PathVariable("linkId") String linkId, HttpServletRequest request, HttpServletResponse response) throws IOException {
        if(log.isDebugEnabled()){
            Enumeration headerNames = request.getHeaderNames();
            while (headerNames.hasMoreElements()){
                String name	=(String) headerNames.nextElement();
                String value = request.getHeader(name);
                log.debug("req head {}:{}",name,value);
            }
        }
        EventRes res = linkService.event(new EventReq(linkId
                , cn.hutool.extra.servlet.ServletUtil.getClientIP(request,"CF-Connecting-IP")
                , request.getHeader(HttpHeaders.USER_AGENT)
                , request.getHeader(HttpHeaders.REFERER)));

        // 若linkType 为data,则返回json数据
        if(res.getLinkType() == LinkType.DATA){
            return res;
        }

        if(res.getUrl().indexOf("?")==-1){
            res.setUrl(res.getUrl()+"?e="+res.getUuid());
        }else{
            res.setUrl(res.getUrl()+"&e="+res.getUuid());
        }
        response.sendRedirect(res.getUrl());
        return "SUCCESS";
    }


}
